package org.example.handler;

import lombok.extern.slf4j.Slf4j;
import org.example.common.Constants;
import org.example.common.LoginVo;
import org.example.utils.JWTUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.web.authentication.logout.LogoutHandler;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;


/**
 * 退出登录执行处理器
 */
@Slf4j
public class CustomLogoutHandler implements LogoutHandler {

   // private RedisTemplate redisTemplate;

    @Autowired
    private RedisTemplate<String, Object> redisTemplate;

    public void setRedisTemplate(RedisTemplate redisTemplate) {
        this.redisTemplate = redisTemplate;
    }

    @Override
    public void logout(HttpServletRequest request, HttpServletResponse response, Authentication authentication) {
        String header = request.getHeader(Constants.TOKEN);
        if (header != null && !header.isEmpty()) {
            try {
                LoginVo loginVo = JWTUtils.parseToken(header);
                log.info("退出用户信息：{}", loginVo.getUserId());

                // 清除 Redis 中的 Token
                String redisKey = Constants.TOKEN + loginVo.getUserId();
                redisTemplate.delete(redisKey);
                log.info("已清除 Redis 中的用户 Token：{}", redisKey);

                // 清除 Spring Security 的认证信息
                SecurityContextHolder.clearContext();
                log.info("已清除 Spring Security 的认证信息");

                // 设置响应状态
                response.setStatus(HttpServletResponse.SC_OK);
                response.getWriter().write("退出登录成功");
            } catch (Exception e) {
                log.error("Token 解析失败：{}", e.getMessage());
                response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
                try {
                    response.getWriter().write("退出登录失败");
                } catch (IOException ex) {
                    throw new RuntimeException(ex);
                }
            }
        } else {
            log.warn("请求头中未找到 Token");
            response.setStatus(HttpServletResponse.SC_BAD_REQUEST);
            try {
                response.getWriter().write("请求头中未找到 Token");
            } catch (IOException e) {
                throw new RuntimeException(e);
            }
        }
    }
}
